package com.kingsailor.gunsmith.admin.web.controller;

import com.kingsailor.gunsmith.security.LoginUserAccessor;
import com.kingsailor.gunsmith.security.UserAccessControlService;
import com.kingsailor.gunsmith.webmvc.RequestHeaderUtil;
import com.kingsailor.gunsmith.webmvc.ResponseData;
import edu.jetwinner.util.Base64Encoder;
import edu.jetwinner.util.EasyStringUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Controller
public class LoginController {

    private final UserAccessControlService userAccessControlService;

    @Value("${gunsmith.shiro.successUrl:/index}")
    private String loginSuccessUrl;

    public LoginController(UserAccessControlService userAccessControlService) {
        this.userAccessControlService = userAccessControlService;
    }

    @GetMapping("/login")
    public String loginPage() {
        return "login-admin-lte";
    }

    @PostMapping("/login")
    @ResponseBody
    public ResponseData doLoginAction(String username, String password, HttpServletRequest request) {
        boolean rememberMe = "true".equalsIgnoreCase(request.getParameter("rememberMe"));
        username = "admin";
        password = "super123";
        try {
            userAccessControlService.doLoginCheck(username, password, rememberMe);
        } catch (Exception e) {
            String msg = "登录错误！";
            if (EasyStringUtil.isNotEmpty(e.getMessage())) {
                msg = e.getMessage();
            }
//            if (ex.getCode() != null && "50004".equals(ex.getCode())) {
//                return ResponseData.error(ex.getCode(), ex.getMessage());
//            }
            return ResponseData.error(msg);
        }
        if ("json".equalsIgnoreCase(RequestHeaderUtil.getHeader(request, "__ajax"))) {
            LoginUserAccessor accessor = userAccessControlService.getLoginUserAccessor();
            return ResponseData.success("登录成功!").add("sId", accessor.getSessionId())
                    .add("token", Base64Encoder.encode(accessor.getCsrfToken()))
                    .add("expires_in", accessor.getSessionTimeout() / (1000 * 60));
        } else {
            return ResponseData.success("登录成功!").add("index", this.loginSuccessUrl);
        }
    }

    @PostMapping("/Account/login")
    @ResponseBody
    public ResponseData lockLogin(String username, String password, HttpServletRequest request) {
        return doLoginAction(username, password, request);
    }
}
